<template>
  <div class="carousel-container">
    <a-card title="轮播图管理" :bordered="false">
      <!-- 搜索区域 -->
      <a-form layout="inline" :model="queryParams" class="search-form">
        <a-form-item label="使用状态">
          <a-select v-model:value="queryParams.isUsed" placeholder="请选择" style="width: 200px">
            <a-select-option :value="null">全部</a-select-option>
            <a-select-option :value="1">已启用</a-select-option>
            <a-select-option :value="0">未启用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button style="margin-left: 8px" @click="resetQuery">重置</a-button>
        </a-form-item>
      </a-form>

      <!-- 操作按钮区域 -->
      <div class="table-operations">
        <a-button type="primary" @click="handleAdd">新增轮播图</a-button>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="carouselList"
        :pagination="pagination"
        :loading="loading"
        rowKey="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'imageUrl'">
            <a-image
              :src="record.imageUrl"
              :width="80"
              placeholder
              :preview="{
                src: record.imageUrl,
              }"
            />
          </template>
          <template v-if="column.key === 'isUsed'">
            <a-tag :color="record.isUsed === 1 ? 'green' : 'orange'">
              {{ record.isUsed === 1 ? '已启用' : '未启用' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'createTime'">
            {{ formatDateTime(record.createTime) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space size="small">
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button
                type="link"
                size="small"
                :disabled="record.isUsed === 1"
                @click="handleToggleStatus(record)"
              >
                {{ record.isUsed === 1 ? '禁用' : '启用' }}
              </a-button>
              <a-popconfirm
                title="确定要删除此轮播图吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a-button danger type="link" size="small">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 新增/编辑表单弹窗 -->
      <a-modal
        :title="modalTitle"
        v-model:visible="modalVisible"
        :confirm-loading="submitLoading"
        @ok="handleSubmit"
        @cancel="modalVisible = false"
        width="600px"
      >
        <a-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          layout="vertical"
        >
          <a-form-item label="轮播图片" name="imageUrl">
            <div class="upload-wrapper">
              <upload-image
                v-model:value="formState.imageUrl"
                :biz="BIZ_TYPE.CAROUSEL_IMG"
                @upload-success="handleImageUploadSuccess"
              />
            </div>
          </a-form-item>
          <a-form-item label="使用状态" name="isUsed">
            <a-radio-group v-model:value="formState.isUsed">
              <a-radio :value="1">启用</a-radio>
              <a-radio :value="0">禁用</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import {
  listCarouselVoByPageUsingPost,
  addCarouselUsingPost,
  updateCarouselUsingPost,
  deleteCarouselUsingPost,
  getCarouselVoByIdUsingGet
} from '@/api/carouselController'
import dayjs from 'dayjs'
import UploadImage from '@/components/UploadImage.vue'
import { BIZ_TYPE } from '@/constants/upload'

// 查询参数
const queryParams = reactive({
  current: 1,
  pageSize: 10,
  isUsed: null as null | number,
  sortField: 'createTime',
  sortOrder: 'desc'
})

// 表格数据和加载状态
const carouselList = ref<API.CarouselVO[]>([])
const loading = ref(false)
const total = ref(0)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条数据`
})

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: '80px'
  },
  {
    title: '轮播图片',
    dataIndex: 'imageUrl',
    key: 'imageUrl',
    width: '200px'
  },
  {
    title: '使用状态',
    dataIndex: 'isUsed',
    key: 'isUsed',
    width: '100px'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: '180px',
    sorter: true
  },
  {
    title: '操作',
    key: 'action',
    width: '180px'
  }
]

// 弹窗相关
const modalVisible = ref(false)
const modalTitle = ref('新增轮播图')
const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const formState = reactive({
  id: undefined as undefined | number,
  imageUrl: '',
  isUsed: 1
})

// 表单验证规则
const rules = {
  imageUrl: [{ required: true, message: '请上传轮播图片', trigger: 'change' }]
}

// 格式化日期时间
const formatDateTime = (dateTime: string | undefined) => {
  if (!dateTime) return '-'
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

// 获取轮播图列表
const getCarouselList = async () => {
  loading.value = true
  try {
    // 发送查询前调整参数
    const params = { ...queryParams } as API.CarouselQueryRequest
    if (params.isUsed === null) {
      params.isUsed = undefined
    }
    
    const response = await listCarouselVoByPageUsingPost(params)
    if (response && response.code === 0 && response.data) {
      // 处理分页数据
      carouselList.value = response.data.records || []
      pagination.total = response.data.total || 0
      pagination.current = response.data.current || 1
      pagination.pageSize = response.data.size || 10
      total.value = response.data.total || 0
    } else {
      message.error(response?.message || '获取轮播图列表失败')
    }
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
    message.error('获取轮播图列表失败')
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  queryParams.current = pag.current
  queryParams.pageSize = pag.pageSize
  
  // 处理排序
  if (sorter.field && sorter.order) {
    queryParams.sortField = sorter.field
    queryParams.sortOrder = sorter.order === 'ascend' ? 'asc' : 'desc'
  } else {
    queryParams.sortField = 'createTime'
    queryParams.sortOrder = 'desc'
  }
  
  getCarouselList()
}

// 搜索
const handleSearch = () => {
  queryParams.current = 1
  getCarouselList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.isUsed = null
  queryParams.current = 1
  getCarouselList()
}

// 处理图片上传成功
const handleImageUploadSuccess = (url: string) => {
  formState.imageUrl = url
}

// 新增轮播图
const handleAdd = () => {
  modalTitle.value = '新增轮播图'
  formState.id = undefined
  formState.imageUrl = ''
  formState.isUsed = 1
  modalVisible.value = true
}

// 编辑轮播图
const handleEdit = async (record: API.CarouselVO) => {
  try {
    const response = await getCarouselVoByIdUsingGet({ id: record.id })
    if (response && response.code === 0 && response.data) {
      modalTitle.value = '编辑轮播图'
      formState.id = response.data.id
      formState.imageUrl = response.data.imageUrl || ''
      formState.isUsed = response.data.isUsed === undefined ? 1 : response.data.isUsed
      
      modalVisible.value = true
    } else {
      message.error(response?.message || '获取轮播图信息失败')
    }
  } catch (error) {
    console.error('获取轮播图信息失败:', error)
    message.error('获取轮播图信息失败')
  }
}

// 切换状态
const handleToggleStatus = async (record: API.CarouselVO) => {
  try {
    const newStatus = record.isUsed === 1 ? 0 : 1
    const response = await updateCarouselUsingPost({
      id: record.id,
      imageUrl: record.imageUrl,
      isUsed: newStatus
    })
    if (response && response.code === 0 && response.data === true) {
      message.success(`${newStatus === 1 ? '启用' : '禁用'}成功`)
      getCarouselList()
    } else {
      message.error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    message.error('操作失败')
  }
}

// 删除轮播图
const handleDelete = async (record: API.CarouselVO) => {
  try {
    const response = await deleteCarouselUsingPost({ id: record.id })
    if (response && response.code === 0 && response.data === true) {
      message.success('删除成功')
      getCarouselList()
    } else {
      message.error(response?.message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

// 表单提交
const handleSubmit = () => {
  formRef.value?.validate().then(async () => {
    if (!formState.imageUrl) {
      message.error('请上传轮播图片')
      return
    }
    
    submitLoading.value = true
    try {
      let response
      if (formState.id) {
        // 编辑
        response = await updateCarouselUsingPost({
          id: formState.id,
          imageUrl: formState.imageUrl,
          isUsed: formState.isUsed
        })
      } else {
        // 新增
        response = await addCarouselUsingPost({
          imageUrl: formState.imageUrl,
          isUsed: formState.isUsed
        })
      }
      
      if (response && response.code === 0) {
        message.success(`${formState.id ? '修改' : '新增'}成功`)
        modalVisible.value = false
        getCarouselList()
      } else {
        message.error(response?.message || `${formState.id ? '修改' : '新增'}失败`)
      }
    } catch (error) {
      console.error(`${formState.id ? '修改' : '新增'}失败:`, error)
      message.error(`${formState.id ? '修改' : '新增'}失败`)
    } finally {
      submitLoading.value = false
    }
  })
}

onMounted(() => {
  getCarouselList()
})
</script>

<style scoped lang="scss">
.carousel-container {
  padding: 24px;
  
  .search-form {
    margin-bottom: 24px;
  }
  
  .table-operations {
    margin-bottom: 16px;
  }
  
  .upload-wrapper {
    :deep(.ant-upload-select) {
      width: 200px !important;
      height: 200px !important;
    }
    
    :deep(.ant-upload-list-picture-card-container) {
      width: 200px !important;
      height: 200px !important;
    }
  }
}
</style> 